import Mock from 'mockjs'

// get请求从config.url获取参数，post从config.body中获取参数
function param2Obj(url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
    decodeURIComponent(search)
      .replace(/"/g, '\\"')
      .replace(/&/g, '","')
      .replace(/=/g, '":"') +
    '"}'
  )
}

let ProductList = []
const count = 200

// 模拟200条商品数据
for (let i = 0; i < count; i++) {
  ProductList.push(
    Mock.mock({
      id: Mock.Random.guid(),
      name: Mock.Random.ctitle(5, 12), // 商品名称
      price: Mock.Random.float(10, 1000, 0, 2), // 价格，10-1000之间，保留2位小数
      stock: Mock.Random.integer(0, 1000), // 库存，0-1000之间
      image: Mock.Random.image('200x200', Mock.Random.color(), '#FFF', 'png', Mock.Random.word(3, 5)), // 商品图片
      description: Mock.Random.csentence(10, 30), // 商品描述
      category: Mock.Random.pick(['电子产品', '服装', '食品', '家居', '图书', '美妆']), // 商品分类
      createTime: Mock.Random.datetime('yyyy-MM-dd'), // 创建时间
      publishTime: Mock.Random.datetime('yyyy-MM-dd'), // 发布时间
      status: Mock.Random.pick(['上架', '下架', '缺货', '预售']), // 商品状态
      sales: Mock.Random.integer(0, 10000) // 销量
    })
  )
}

export default {
  /**
   * 获取商品列表
   * 参数: name, page, limit, category; name和category可以不填, page,limit有默认值
   * @param name, page, limit, category
   * @return {{code: number, count: number, data: *[]}}
   */
  getProductList: config => {
    const { name, page = 1, limit = 7, category } = param2Obj(config.url)
    
    const mockList = ProductList.filter(product => {
      // 根据name筛选数据
      if (name && product.name.indexOf(name) === -1) return false
      // 根据category筛选数据
      if (category && product.category !== category) return false
      return true
    })
    
    // 分页
    const pageList = mockList.filter((item, index) => 
      index < limit * page && index >= limit * (page - 1)
    )
    
    return {
      code: 200,
      data: {
        list: pageList,
        count: mockList.length, // 数据总条数
        totalPages: Math.ceil(mockList.length / limit) // 总页数
      }
    }
  },
  
  /**
   * 删除商品
   * @param id
   * @return {*}
   */
  deleteProduct: config => {
    const { id } = param2Obj(config.url)
    if (!id) {
      return {
        code: -999,
        message: '参数不正确'
      }
    } else {
      ProductList = ProductList.filter(p => p.id !== id)
      return {
        code: 200,
        message: '删除成功'
      }
    }
  },
  
  /**
   * 添加商品
   * @param name, price, stock, image, description, category, status
   * @return {{code: number, data: {message: string}}}
   */
  createProduct: config => {
    const { name, price, stock, image, description, category, status } = JSON.parse(config.body)
    const now = new Date().toISOString()
    
    ProductList.unshift({
      id: Mock.Random.guid(),
      name: name,
      price: parseFloat(price),
      stock: parseInt(stock),
      image: image || Mock.Random.image('200x200', Mock.Random.color(), '#FFF', 'png', name.substring(0, 3)),
      description: description || Mock.Random.csentence(10, 20),
      category: category || Mock.Random.pick(['电子产品', '服装', '食品', '家居', '图书', '美妆']),
      createTime: now,
      publishTime: now,
      status: status || '上架',
      sales: 0
    })
    
    return {
      code: 200,
      data: {
        message: '添加成功'
      }
    }
  },
  
  /**
   * 修改商品信息
   * @param id, name, price, stock, image, description, category, status
   * @return {{code: number, data: {message: string}}}
   */
  updateProduct: config => {
    const { id, name, price, stock, image, description, category, status } = JSON.parse(config.body)
    
    ProductList.some(p => {
      if (p.id === id) {
        p.name = name
        p.price = parseFloat(price)
        p.stock = parseInt(stock)
        if (image) p.image = image
        if (description) p.description = description
        if (category) p.category = category
        if (status) p.status = status
        return true
      }
    })
    
    return {
      code: 200,
      data: {
        message: '编辑成功'
      }
    }
  },
  
  /**
   * 获取商品详情
   * @param id
   * @return {{code: number, data: {product: object}}}
   */
  getProductDetail: config => {
    const { id } = param2Obj(config.url)
    const product = ProductList.find(p => p.id === id)
    
    if (!product) {
      return {
        code: 404,
        message: '商品不存在'
      }
    }
    
    return {
      code: 200,
      data: {
        product: product
      }
    }
  }
}